import { ColumnsType } from 'antd/es/table';
import classNames from 'classnames';
import { FC } from 'react';

import { Category } from '@/components/base/Category';
import { Table } from '@/components/base/Table';
import { useDictStore } from '@/store/dict';

interface VariablesTableProps {
  dataSource: VariableItem[];
  actions?: ColumnsType<VariableItem>[number];
  title?: string;
  className?: string;
}

export const VariablesTable: FC<VariablesTableProps> = memo((props) => {
  const dictStore = useDictStore();
  const columns: ColumnsType<VariableItem> = useMemo(() => {
    return [
      { title: '参数名称', dataIndex: 'varName', key: 'varName' },
      { title: '字段Key', dataIndex: 'varLabel', key: 'varLabel' },
      {
        title: '类型',
        dataIndex: 'varType',
        key: 'varType',
        render: (text: string) => {
          return <>{dictStore.fieldTypeMap[text]}</>;
        }
      },
      {
        title: '默认值',
        dataIndex: 'initValue',
        key: 'initValue',
        render: (text: string, record: VariableItem) => {
          const label = record.options?.find((re) => re.value === text)?.label;
          return <>{label || text}</>;
        }
      }
    ];
  }, [dictStore.fieldTypeMap]);

  useEffect(() => {
    if (props.actions) {
      columns.push(props.actions);
    }
  }, [columns, props.actions]);

  return (
    <div className={classNames(props.className, 'variables-table')}>
      {props.title && <Category className="pb-12">{props.title}</Category>}
      <Table<VariableItem> rowKey="varName" pagination={false} columns={columns} dataSource={props.dataSource} />
    </div>
  );
});
